/* eslint-disable no-param-reassign */
import { Button, Form, List } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import { useStore } from '@/hooks';

const FromItem = Form.Item;

const DataForm = ({ modal, onCancel }) => {
  const { record } = modal;
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [log] = useState(() => observable({}));
  const [list, setList] = useState([]);
  const { logStore: store } = useStore();

  useEffect(() => { if (modal.toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    (async () => {
      if (record) {
        const data = _.cloneDeep(record);
        editCtx.origin = _.cloneDeep(data);
        _.assign(log, data);
        if (JSON.stringify(data?.args) !== '{}') {
          const res = store.flattenObject(data.args);
          // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
          const mapList = Object.entries(res).map(([key, value]) => ({
            title: key,
            value,
          }));
          setList([...mapList]);
        }
      }
    })();
  }, []);

  const handleCancel = () => {
    onCancel?.();
  };

  return (
    <>
      <List
        size="small"
        header={<div>{t`参数列表`}</div>}
        dataSource={list}
        renderItem={(item, i) => (
          <List.Item
            key={i}
            extra={item.value}
            title={`args : ${item.title}`}
          />
        )}
      />
      <DrawerFooter>
        <FromItem>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </>

  );
};

export default observer(DataForm);
